<?php 

//if(!isset($_SESSION['sess_uid']) || (trim($_SESSION['sess_role']) == '')) {
session_start();
if (!isset($_SESSION['sess_uid'])){
	header("location: save.php");
	exit();
 } else
 
 {


require_once('db.php');

//Load Default Parameter :
$sql = "select * from tb_setting";
$setting  = @mysql_query($sql,$link);
$data	  = mysql_fetch_array($setting, MYSQL_ASSOC);


?>


<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <base href="" />
    <title>eTaxware : <?php echo $data['site_name']; ?></title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <script type="text/javascript">

</script>
	<link rel="shortcut icon" href="assets/images/icon.png" />
    <script type="text/javascript">if(parent.frames.length>0)top.location='process.php?module=pos'</script>
    <link rel="stylesheet" href="assets/css/bootstrap.css" type="text/css" charset="utf-8">
    <link rel="stylesheet" href="assets/css/posajax.css" type="text/css" charset="utf-8">
    <link rel="stylesheet" href="assets/css/non-responsive.css" type="text/css">
    <link rel="stylesheet" href="assets/css/print.css" type="text/css" media="print">
  
	<script src="assets/js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="assets/js/jquery.keyboard.min.js"></script> 	
	
    <script src="assets/js/purl.js"></script>
	
	<link href="assets/css/jquery.bxslider.css" rel="stylesheet" />  
	<script src="assets/js/jquery.bxslider.min.js"></script> 

	<script type="text/javascript" src="assets/js/bootstrap.js"></script> 
	<script type="text/javascript" src="assets/js/bootbox.js"></script>
	
	<script type="text/javascript">
	$(document).ready(function(){
		$('.bxslider').bxSlider({minSlides:3,maxSlides:3,slideWidth:600,slideMargin:0,ticker:false,infiniteLoop:false,hideControlOnEnd:true,mode:'horizontal'});
		
	});
	</script> 
	
	
    <style>.btn-product { background: #EEE; border:1px solid #EEE; border-bottom: 0; }.btn-con .btn-default{ height: 43px; }</style>    
	<style>.ui-keyboard { height: 0 !important; display: none !important; }</style>    


</head>
    <body>
<div id="wrap">

<div class="navbar navbar-static-top navbar-inverse">
<div class="container">
	<div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse"> 
		<span class="icon-bar"></span> 
		<span class="icon-bar"></span> 
		<span class="icon-bar"></span> 
		</button>
        <a class="navbar-brand">eTaxware : <?php echo $data['site_name']; ?></a>
	</div>
	
        <ul class="nav navbar-nav">        
        <li><a href="process.php?module=settings" class="tip" data-placement="right" title="Home">
			<i class="glyphicon glyphicon-home"></i>
			</a>
		</li>
        <li><a href="process.php?module=settings&view=system_setting" class="tip" data-placement="right" title="Settings">
			<i class="glyphicon glyphicon-cog"></i>
			</a>
		</li>
        <li><a href="process.php?module=sales" class="tip" data-placement="right" title="Sales">
			<i class="glyphicon glyphicon-list"></i>
			</a>
		</li>
		</ul>
	
		<ul class="nav navbar-nav navbar-right">
		<li><a class="hov"><span id="cur-time"></span></a></li>	
		<li><a href="#" class="tip" data-placement="left" title="Saved Orders">
			<i class="glyphicon glyphicon-shopping-cart"></i>
			</a>
		</li>
		<li><a href="#" class="tip" data-placement="left" title="Current Sales">
			<i class="glyphicon glyphicon-tasks"></i>
			</a>
		</li>
        <li><a href="logout.php" class="tip" data-placement="left" title="Keluar Click Disini!">
			<i class="glyphicon glyphicon-log-out"></i>
			</a>
		</li>
		
		</ul>
		
		
        
		
		
</div>
</div>


<div class="container">
    <div id="wrapper">
          <div id="content">
        <div class="c1">
              <div class="pos">
                                    <div id="pos">
                  <form method="post" accept-charset="utf-8"><div style="display:none">
<input type="hidden" name="session_id" value="" />
</div>        

<div class="well well-sm" id="leftdiv">
              
                <div id="printhead">
                      <h2><strong>eTaxware</strong></h2>
<p>
<br>
                                                                                             
</p>                      <p>
                                    </p>
                    </div>
<div id="print">
                      <table width="100%" border="0" cellpadding="0" cellspacing="0" class="table table-striped table-condensed table-hover miantable" style="margin:5px 0 0 0;">
                    <thead>
                          <tr class="success">
                        <th style="width: 6%" class="satu">X</th>
                        <th style="width: 58%">Product</th>
						
                        <th style="width: 7%">Qty</th>
                        <th style="width: 24%">Price</th>
                        <th style="width:19px; padding:0;">&nbsp;</th>
                      </tr>
                        </thead>
                  </table>
            <div id="prodiv">
                    <div id="protbldiv" class="nano">
                          <div class="content">
                        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="table table-striped table-condensed table-hover protable"  id="saletbl" style="margin:0;">
                              <tbody>
                          </tbody>
                            </table>
                      </div>
                          <div style="clear:both;"></div>
                        </div>
            </div>
                     
                      <div id="totaldiv">
                    <table id="totaltbl" class="table table-striped table-condensed totals" style="margin-bottom:2px;">
                          <tbody>
                        <tr class="success">
                              <td width="25%">Total Items</td>
                              <td><span id="count">0</span></td>
                              <td width="25%">Total</td>
                              <td class="text_right" colspan="2"><span id="total">0.00</span></td>
                            </tr>
                        <tr class="success">
                              <td width="25%">Discount  
							  </td>
                              <td><span id="ds_con">0.00</span></td>
                              <td width="25%">Tax                            </td>
                              <td class="text_right"><span id="ts_con">0.00</span></td>
                            </tr>
						<tr class="success">
                              <td width="25%">  
							  </td>
                              <td></td>
                              <td width="25%">S-Charge                            </td>
                              <td class="text_right"><span id="cs_con">0.00</span></td>
                            </tr>	
                        <tr class="success">
                              <td colspan="2">Grand Total</td>
                              <td class="text_right" colspan="2"><span id="total-payable">0.00</span></td>
                            </tr>
                      </tbody>
                        </table>
                  </div>
                    </div>
                <div id="botbuttons" style="text-align:center;margin-bottom:0px;">
                    <button type="button" class="btn btn-danger" id="cancel" style="width:100px;">Batal</button>
                    <button type="button" class="btn btn-info" id="hold" style="width:120px;">Simpan Order</button>
                    <button type="button" class="btn btn-success" id="payment" style="margin-right:0; width:150px;">Bayar</div>

                <input type="hidden" name="customer" id="customer" value="3" />
                <input type="hidden" name="inv_tax" id="tax_val" value="<?php echo $data['def_tax'];?>" />
                <input type="hidden" name="inv_discount" id="discount_val" value="<?php echo $data['def_disc'];?>" />
				<input type="hidden" name="inv_scharge" id="scharge_val" value="<?php echo $data['def_scharge'];?>" />
				
                <input type="hidden" name="rpaidby" id="rpaidby" value="cash" style="display: none;" />
                <input type="hidden" name="count" id="total_item" value="" />
                <input type="hidden" name="delete_id" id="is_delete" value="" />
                <input type="hidden" name="hold_ref" id="hold_ref" value="" />
                <input type="hidden" name="paid_val" id="paid_val" value="" />
                <input type="hidden" name="cc_no_val" id="cc_no_val" value="" />
                <input type="hidden" name="cc_holder_val" id="cc_holder_val" value="" />
                <input type="hidden" name="cheque_no_val" id="cheque_no_val" value="" />
                <span id="hidesuspend"></span>
                <input type="submit" id="submit" value="Submit Sale" style="display: none;" />
              </div>
                  </form>
				<div id="cp">
			
   					<ul class="bxslider">

						<?php	$sql 		= "select * from tb_category order by id asc";
								$result 	=  mysql_query($sql,$link);
								while($data_get=@mysql_fetch_array($result)){	
						?>
									<li><button type="button" class="btn btn-cat" value="<?php echo $data_get['id'];?>" id="category-<?php echo $data_get['id'];?>"><?php echo $data_get['cat_name'];?></button></li>
						<?php
								}
								
						?>
					</ul>
		<div id="lefttop">
                      <input name="code" id="cari_product" class="form-control input-sm" placeholder="Cari Product ID" style="margin-bottom: 10px;" />
					  <input name="s_result" id="s_result" class="form-control input-sm" placeholder="" readonly="readonly"  style="margin-bottom: 10px;" />
        </div>
						<div class="btn-con">
						<button id="previous" type="button" class="btn btn-default" style='z-index:10002;'>
						<i class="glyphicon glyphicon-chevron-left"></i>
						</button><button id="next" type="button" class="btn btn-default" style='z-index:10003;'>
						<i class="glyphicon glyphicon-chevron-right"></i></button>
						</div>
				
				
				
						<div id="ajaxproducts">
							<div class="btn-product clearfix">
							<div id="proajax">
              
					
							</div>
							</div>	
					
							
						  
						</div>


						
				</div>
			  </div>
			  
                  <div style="clear:both;"></div>
                </div>
            <div style="clear:both;"></div>
          </div>
            </div>
        <div style="clear:both;"></div>
      </div>
        </div>
  </div>
    </div>

<div id="footer">
      <div class="container">
	<p class="credit"> [ UserID : <?php echo $_SESSION["sess_uid"] ?>, Role : <?php echo $_SESSION["sess_role"] ?> ]</p>
  </div>
    </div>
<div id="loading" style="display: none;">
      <div class="blackbg"></div>
      <div class="loader"><img src="assets/images/loader.gif" alt="" />
</div>
    </div>
	
	
<div class="modal fade" id="saleModal" tabindex="-1" role="dialog" aria-labelledby="saleModalLabel" aria-hidden="true"></div>
<div class="modal fade" id="opModal" tabindex="-1" role="dialog" aria-labelledby="opModalLabel" aria-hidden="true">ABC</div>


<!-- Payment Modal Form -->
<div class="modal fade" id="payModal" tabindex="-1" role="dialog" aria-labelledby="payModalLabel" aria-hidden="true">
      <div class="modal-dialog">
    <div class="modal-content">
          <div class="modal-header modal-primary">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove"></i></button>
        <h4 class="modal-title" id="payModalLabel">
              PAYMENT            </h4>
      </div>
          <div class="modal-body">
        <table class="table table-striped" style="margin-bottom:0;">
              <tbody>
            <tr>
                  <td width="50%">Customer</td>               
			<!--
				  <a href="#" class="btn btn-primary btn-xs showCModal"><i class="glyphicon glyphicon-plus-sign"></i>
                    Add Customer                    </a>
			-->		
					
                  <td width="50%"><span class="inv_cus_con">
                    <select id="_cust" class="form-control pcustomer" style="padding: 2px !important; height: auto !important;">
                    <?php
					$sql 		= "select * from tb_customer order by cust_id asc";
								$result =  mysql_query($sql,$link);
								while($data_get=@mysql_fetch_array($result)){	
												
					?>
					<option value="<?php echo $data_get['cust_id'];?>"><?php echo $data_get['cust_name'];?></option>
					<?php
								}
								
								
					
					?>
					</select>
                    </span></td>
                </tr>
			
			<tr>
                  <td>Total Items                </td>
                  <td><span style="background: #FFFF99; text-weight: bold; padding: 5px 10px; color: #000;"><span id="fcount"></span></span></td>
            </tr>


			
            <tr>
                  <td>Grand Total   </td>
                  <td><span style="background: #FFFF99; padding: 5px 10px; text-weight: bold; color: #000;"><span id="twt"></span></span></td>
            </tr>
           
            </tr>
            
          <td>Paid by              </td>
            <td><select name="paid_by" id="paid_by" class="form-control" style="padding: 2px !important; height: auto !important;">
                <option value="CASH">
                Cash                </option>
                <option value="CC">
                Credit Card                </option>
                <option value="DC">
                Debet Card                </option>
              </select></td>
          </tr><tr class="pcash">
            <td>Paid              </td>
            <td><input type="text" id="paid-amount" class="form-control"  style="padding: 2px !important; height: auto !important;" /></td>
          </tr>
              <tr class="pcash">
            <td>Return Change                  </td>
            <td><span style="background: #FFFF99; padding: 5px 10px; text-weight: bold; color: #000;" id="balance"></span></td>
          </tr>
          
		   <tr class="pcc" style="display:none;">
            <td>Card No                  </td>
            <td><input type="text" id="pcc" class="form-control"  style="padding: 2px !important; height: auto !important;" /></td>
          </tr>
		  
              <tr class="pcc" style="display:none;">
            <td>Card Holder                  </td>
            <td><input type="text" id="pcc_holder" class="form-control"  style="padding: 2px !important; height: auto !important;" /></td>
          </tr>
              
		<tr class="pcc" style="display:none;">
            <td>Issuer Bank                  </td>
            <td>
			<select name="issuer_bank" id="paid_by" class="form-control" style="padding: 2px !important; height: auto !important;">
			<?php
					$sql 		= "select * from tb_bank order by bank_id asc";
								$result =  mysql_query($sql,$link);
								while($data_get=@mysql_fetch_array($result)){	
												
			?>
					<option value="<?php echo $data_get['bank_id'];?>"><?php echo $data_get['bank_name'];?></option>
			<?php
								}
					
			?>
            </select>
			</td>
			  
          </tr>	  
			  
                </tbody>
              
            </table>
      </div>
          <div class="modal-footer">
		 
        <button type="button" class="btn btn-primary" data-dismiss="modal" style="margin-right:0; width:150px;">
            CANCEL            </button>
        <button class="btn btn-success" id="submit-sale" style="margin-right:0; width:150px;">
            BAYAR            </button>
      </div>
        </div>
  </div>
    </div>
	
	

	
<div class="modal fade" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="proModalLabel" aria-hidden="true">
      <div class="modal-dialog">
    <div class="modal-content">
          <div class="modal-header modal-primary">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove"></i></button>
        <h4 class="modal-title" id="proModalLabel">
              Add Customer            </h4>
      </div>
          <div class="modal-body">
        <div id="customerError"></div>
        <div class="row">
              <div class="col-xs-12">
            <div class="form-group">
                  <label class="control-label" for="code">
                Name              </label>
                  <input type="text" name="name" value="" class="form-control input-sm" id="cname" />                </div>
          </div>
            </div>
        <div class="row">
              <div class="col-xs-6">
            <div class="form-group">
                  <label class="control-label" for="cemail">
                Email Address              </label>
                  <input type="text" name="email" value="" class="form-control input-sm" id="cemail" />                </div>
          </div>
              <div class="col-xs-6">
            <div class="form-group">
                  <label class="control-label" for="phone">
                Phone              </label>
                  <input type="text" name="phone" value="" class="form-control input-sm" id="cphone" />                </div>
          </div>
            </div>
        <div class="row">
              <div class="col-xs-6">
            <div class="form-group">
                  <label class="control-label" for="cf1">
                Custom Field 1              </label>
                  <input type="text" name="cf1" value="" class="form-control input-sm" id="cf1" />                </div>
          </div>
              <div class="col-xs-6">
            <div class="form-group">
                  <label class="control-label" for="cf2">
                Custom Field 2              </label>
                  <input type="text" name="cf2" value="" class="form-control input-sm" id="cf2" />                </div>
          </div>
            </div>
            <input type="hidden" id="show_m" value="">
      </div>
          <div class="modal-footer" style="margin-top:0;">
        <button type="button" class="btn btn-primary" data-dismiss="modal">
            Close            </button>
        <button class="btn btn-success" id="add-customer">
            Add Customer            </button>
      </div>
        </div>
  </div>
 </div>
	
	
<!-- Modal : Saved Order -->	
<div class="modal fade" id="susModal" tabindex="-1" role="dialog" aria-labelledby="susModalLabel" aria-hidden="true">
      <div class="modal-dialog">
    <div class="modal-content">
          <div class="modal-header modal-primary">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove"></i></button>
        <h4 class="modal-title" id="susModalLabel">
              Save Order            </h4>
      </div>
          <div class="modal-body">
        <table class="table table-striped" style="margin-bottom:0;">
              <tbody>
            <tr>
                  <td width="50%">Customer                <a href="#" class="btn btn-primary btn-xs showCModal"><i class="glyphicon glyphicon-plus-sign"></i>
                    Add Customer                    </a></td>
                  <td width="50%"><span class="inv_cus_con">
                    <select class="form-control pcustomer" style="padding: 2px !important; height: auto !important;">
                    <option value="3">Walk-in Client</option><option value="3">Table A</option><option value="3">Table B</option><option value="4">Member A</option><option value="5">Member B</option></select>
                    </span></td>
                </tr>
            
              <tr class="pcash">
            <td>Order Tags         :</td>
            <td><input type="text" name="hold_v" value="" class="form-control input-sm" id="hold_ref_v" /></td>
          
                </tbody>
              
            </table>
      </div>
          <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">
            Close            </button>
        <button class="btn btn-success" id="submit-hold">
            Submit            </button>
      </div>
        </div>
  </div>
</div>



<!-- Modal : Todays Sale -->
<div class="modal fade" id="curr_sales" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header modal-primary">
			<h4 class="modal-title" id="myModalLabel">Current Sales Summary</h4>
		</div>
        <div class="modal-body">
        <table class="table table-striped" style="margin-bottom:0;">
        <tbody>
            <tr>
                  <td width="50%">SALES BY CASH</td>
                  <td width="2%">:</td><td width="48%"><span id="cs_cash"></span></td>
            </tr>
            <tr>
                  <td width="50%">SALES BY CREDIT CARD</td>
                  <td width="2%">:</td><td width="48%"><span id="cs_cc"></span></td>
            </tr>            
            <tr>
                  <td width="50%">SALES BY DEBIT CARD</td>
                  <td width="2%">:</td><td width="48%"></td>
            </tr>   
            <tr>
                  <td width="50%">TOTAL SALES</td>
                  <td width="2%">:</td><td width="48%"></td>
            </tr>  			
        </tbody>              
        </table>
		</div>
        <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal" style="width:120px;">CLOSE</button>
        </div>
    </div>
	</div>
</div>


<script type="text/javascript">
var KB = 0;
var DTIME = 1;
var count = 1;
var total = 0;
var an = 1;
var rt = 1;
var ids = new Array();
var p_page = 6;
var page = 0;
var cat_id = 1;
var sproduct_name;
var slast;
var total_cp = 0;
var next = 0;
var prev = 0;
var userid = "cashier-1";
var uid	   = "1";

$(document).ready(function(){
	
	LoadFavourite();
	
	var before_qty = 1;
	$(".nkb-input").live("focus",function(){before_qty=parseInt($(this).val())});
	$(".nkb-input").live("keypress",function(e){
		if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        bootbox.alert("Digits Only..!");
		$(this).val(before_qty);
		$(this).focus();
        return false;
	}
	})
	
	
	$('a[title="Current Sales"]').click(function(ev) {
		$('#loading').show();
		var d = new Date(); var curr_dt = d.getFullYear()+'/'+d.getMonth()+'/'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
		ev.preventDefault();
		var msg = '<table class="table table-striped" style="margin-bottom:0;"><tbody>';
		$.ajax({type:"GET",async:false,url:"process.php?module=pos&view=current_sales",
					data:{prodcat_status : 'F'},
					dataType:"html",
					success:function(data){
						$('#loading').hide();
						msg += data;
						//bootbox.alert('Data : '+data);
					}
		});
		msg += '</tbody></table>';
		bootbox.dialog({
				message: msg,
				title: "<h3>Current Total Sales</h3>"+'<h4>'+curr_dt+'</h4>',
				buttons: {
					success: {
					  label: "CLOSE"
					}
				}
				
		});
		return false;
	});
			

	
	function LoadFavourite(){
		var data = 1;
			$.ajax({type:"GET",async:false,url:"process.php?module=pos&view=getFavourite",
					data:{prodcat_status : 'F'},
					dataType:"html",
					success:function(data){
						cat_id=data;
					}
			});
			
				
			page = 0; 
		
			$('#loading').show();
			
			//alert('cat_id : ' +cat_id+' Data : '+data);
			$.ajax({
				type:"get",
				url:"process.php?module=pos&view=catalog",
				data:{category_id:cat_id,per_page:p_page},
				dataType:"html",
				success:function(data){
					$('#proajax').empty();
					var newPrs=$('<div></div>');
					newPrs.html(data);
					newPrs.appendTo("#proajax")
				}
			}).done(function(){
				$.ajax({
					type:"get",async:false,url:"process.php?module=pos&view=total_cp",data:{category_id:cat_id},dataType:"html",success:function(data){total_cp=data}
				}); 
				if (total_cp>0){page=1}else{page=0}
				$('#loading').hide();
				add_row();
				
				
			})
		//}
	
	}
	
	//function get pagination
	function getPagination(count){
      paginationCount= Math.floor(count / p_page);
      paginationModCount= count % p_page;
      if((paginationModCount)!=0){
               paginationCount++;
      }
      return paginationCount;
	}
	
	$('#next').click(function(){
		if (page<getPagination(total_cp)){
			next = page+1;
			$('#loading').show();
			$.ajax({type:"get",url:"process.php?module=pos&view=catalog",
			data:{category_id:cat_id,per_page:p_page,pageId:next},dataType:"html",success:function(data){$('#proajax').empty();var newPrs=$('<div></div>');newPrs.html(data);newPrs.appendTo("#proajax")}}
			).done(
				function(){
					page = next;
					prev = page-1;
					add_row();
					$('#loading').hide()
				}
			)
		}
		
	});
	
	
	$('#previous').click(function(){
		if (page>1){
				prev = page - 1;
				$('#loading').show();
								
				$.ajax({
					type:"get",url:"process.php?module=pos&view=catalog",
					data:{category_id:cat_id,per_page:p_page,pageId:prev},dataType:"html",success:function(data){$('#proajax').empty();var newPrs=$('<div></div>');newPrs.html(data);newPrs.appendTo("#proajax")}
				}).done(function(){
					page = prev;
					next = page+1;
					add_row();
					$('#loading').hide();
				
					
				})
			}
	});
	
	
	//display product by category 
	$('button[id^="category-"]').click(function(){
			page = 0; 
		
			$('#loading').show();
			cat_id=$(this).val();
			$.ajax({
				type:"get",
				url:"process.php?module=pos&view=catalog",
				data:{category_id:cat_id,per_page:p_page},
				dataType:"html",
				success:function(data){
					$('#proajax').empty();
					var newPrs=$('<div></div>');
					newPrs.html(data);
					newPrs.appendTo("#proajax")
				}
			}).done(function(){
				$.ajax({
					type:"get",async:false,url:"process.php?module=pos&view=total_cp",data:{category_id:cat_id},dataType:"html",success:function(data){total_cp=data}
				}); 
				if (total_cp>0){page=1}else{page=0}
				$('#loading').hide();
				add_row();	
				
			})
		//}
	})
//generate id sale , order	
function GenerateID(code){
	var d = new Date();
	var c_d = d.getDate();
	var c_mo = d.getMonth();
	var c_y = d.getFullYear();
	var c_h = d.getHours();
	var c_mi = d.getMinutes();
	var c_s = d.getSeconds();
	var id = "";
	curr_datetime = c_y+'-'+c_mo+'-'+c_d+' '+c_h+':'+c_mi+':'+c_s;
	
	if (code=='BID'){
		id = 'B'+c_y+c_mo+c_d+c_h+c_mi+c_s+'-'+uid;
	} else 
	if (code=='OID') {
		id = 'O'+c_y+c_mo+c_d+c_h+c_mi+c_s+'-'+uid;
	}
	
	return id;
}



//Submit Form :
function buildPaymentJson(){
	var items = [];
	var arrJson = {} ;
	
	var bill_id = GenerateID('BID');
	var order_id = GenerateID('OID');
	var cust = $("#_cust").find('option:selected').val();
	
	sale_items = $( "#saletbl" ).find('button[id^="del-"]');
	var i = 0;
	sale_items.each(function(index) {
		i = index+1;
		//console.log('i : '+i+' index : '+index);
		var prod_id = $( "#saletbl" ).find('input[id^="product-'+i+'"]').attr('id');
		var prod_nam= $( "#saletbl" ).find('input[name^="product'+i+'"]').attr('name');
		
		var len = prod_id.length-prod_nam.length-1;
		prod_id = prod_id.substr(prod_nam.length+1,len);
		
		var qty = $( "#saletbl" ).find('input[id^="quantity-'+i+'"]').val();
	
		//alert ('Len : '+len+' prod id : '+prod_id+' Prod Name : '+prod_nam+' qty : '+qty);
		//alert($(this).attr("id") +':' + $(this).attr("name") +':'+ $(this).val());
		//alert('prod_id : '+prod_id+' | prod_name : '+prod_nam+' | Qty : '+qty);
		
		var item = {
			"order_id" : order_id,
			"prod_id" : prod_id,
			"qty" : qty,
			"customer" : cust,
			"user_id" : userid,
			"status" : 'P',
			"bill_id" : bill_id,
			"order_tag" : ""
		};
		
		items.push(item); 
	})
	//alert(items[0].prod_id+' : '+items[0].qty);
	
	 
	var paid = $("#paid-amount").val();
	var change = $("#balance").text();
	if (trim(paid)==''){paid="0.00";}
	if (trim(change)==''){change="0.00";}
	//build json for posting payment :
	ArrJson = {
	"bill" : {
		"bill_id"		:   bill_id,
		"tot_item"		:	$("#count").text(),
		"total"			:	$("#total").text(),
		"tax"			:	$("#ts_con").text(),
		"s_charge"		:   $("#s_charge").text(),
		"discount"		:	$("#ds_con").text(),
		"grand_tot"		:	$("#total-payable").text(),
		"paid"			:	paid,
		"change"		:	change,
		"paidby"		:	$("#paid_by option:selected").val(),
		"card_num"		:	$("#pcc").text(),
		"card_holder"	:	$("#pcc_holder").text(),
		"customer"		:	cust,
		"userid"		:	userid,
		//"datetime"		:   curr_datetime, no need db autoupdate
		"status"		:	'P',
		"reff_id"		:	''
		},
	"items" : items 	
	}

 		//alert('bill no :'+ArrJson.bill.bill_id);
/*		alert('Cust :'+ArrJson.bill.customer);
		alert('items :'+ArrJson.items[0].prod_id+' Qty : '+ArrJson.items[0].qty); */
		
		return ArrJson;
}
	
$('#submit').click(function(){
	
	var json2send = buildPaymentJson();
	console.log(JSON.stringify(json2send));
	
	$.ajax({
				type:"POST",
				async:false,
				//url:"process.php?module=pos&view=payment",
				url:"payment.php?sess_id=",
				data:{json: JSON.stringify(json2send)},
				dataType:"html",
				success: function (data, textStatus, jqXHR) {
                    console.log('Sucess => data : '+data+' ,status : '+textStatus+' ,jqXHR : '+jqXHR);
					bootbox.alert('<em>Payment : '+textStatus+'</em>. Bill ID : '+data);
                },
				 error: function (xhRequest, ErrorText, thrownError) {
					bootbox.alert("Failed to process request correctly, please try again");
					console.log('xhRequest: ' + xhRequest + "\n");
					console.log('ErrorText: ' + ErrorText + "\n");
					console.log('thrownError: ' + thrownError + "\n");
				}
	})
})
//----------------------------
	

	
	$("#payModal").on('click','.showCModal',function(){
		$('#payModal').modal('hide');
		$('#show_m').val('pay');
		$('#customerModal').modal('show');
		return false
	});
		
	
	$("#susModal").on('click','.showCModal',function(){
		$('#susModal').modal('hide');
		$('#show_m').val('sus');
		$('#customerModal').modal('show');
		return false
	});
	
	$('#customerModal').on('hide.bs.modal',function(){
		if($('#show_m').val()=='pay'){
			$('#payModal').modal('show')
		}
		
		if($('#show_m').val()=='sus'){
			$('#susModal').modal('show')
		}
	});
			
			
	$('#opModal').bind().on('click','a',function(){
/* 		var pg=$.url($(this).attr("href")).param("per_page");
		$.get('process.php?module=pos&view=current_sales&per_page='+pg,function(data){
			$(".html_con").html(data.pd);
			$(".page_con").html(data.page)
		},"json"); */
		bootbox.alert("Current Sales Clicked bind");
		//return false
	});

	

		
	$('.sus_sale').live('click',function(e){
		var sid=$(this).attr("id");
		if(an>1){
			bootbox.confirm("<strong>sale data anda akan batal.</strong> <br>anda yakin meninggalkan halaman sale?",function(gotit){
						if(gotit==false){return true}else{window.location.href="process.php?module=pos&suspend_id="+sid}
					}
			)
		}else{
			window.location.href="process.php?module=pos&suspend_id="+sid
		}
		return false
	});
		
	$('a').each(function(){
		$(this).click(function(e){
			var href=$(this).attr("href");if((href!='#'&&an>1)&&!$(this).hasClass("external")){e.preventDefault();bootbox.confirm("<strong>Data sales anda belum disimpan..</strong> <br>Anda yakin akan meninggalkan halaman ini?",function(gotit){if(gotit==false){return true}else{window.location.replace(href)}})}})
	});
	
	
	//Handling Delete Items :	
	$("#saletbl").on("click",'button[class^="del_row"]',function(){
		var delID=$(this).attr('id');
		var dl_id=delID.split("-");
		var rw_no=dl_id[1];
		var p1=$('#price-'+rw_no);
		var q1=$('#quantity-'+rw_no);
		var row_price=parseFloat(p1.val()*q1.val());
		var row_quantity=parseInt(q1.val());
		
		total=total-row_price;
		current=parseFloat(total).toFixed(2);
		count=count-row_quantity;
		
			/* var ds=$('#discount_val').val();
			if(ds.indexOf("%")!==-1){
				var pds=ds.split("%");
				var discount=(total*parseFloat(pds[0]))/100;
				var g_total=(total+parseFloat($('#ts_con').text()))-discount;
				$("#ds_con").text(discount.toFixed(2))
			}else{
				var g_total=(total+parseFloat($('#ts_con').text()))-parseFloat(ds);
				$("#ds_con").text(parseFloat(ds).toFixed(2))
			}
			
			var ts=$('#tax_val').val();
			if(ts.indexOf("%")!==-1){
				var pts=ts.split("%");
				var tax=(total*parseFloat(pts[0]))/100;
				var g_total=(total+tax)-parseFloat($('#ds_con').text());
				$("#ts_con").text(tax.toFixed(2))
			}else{
				var g_total=(total+parseFloat(ts))-parseFloat($('#ds_con').text());
				$("#ts_con").text(parseFloat(ts).toFixed(2))
			} */
			
		var ds=$('#discount_val').val();
				
		//handling with or without % for Discount.
		if(ds.indexOf("%")!==-1) {
			var pds=ds.split("%");
			var discount=(current*parseFloat(pds[0]))/100;
		}else{
			var discount=parseFloat(ds).toFixed(2);
		}
		
		//handling with or without % for Tax.
		var ts=$('#tax_val').val();
		if(ts.indexOf("%")!==-1) {
			var pts=ts.split("%");
			var tax=(current*parseFloat(pts[0]))/100;
		}else{
			var tax=parseFloat(ts).toFixed(2);
		}
		
		//handling with or without % for s_charge.
		var cs=$('#scharge_val').val();
		if(cs.indexOf("%")!==-1) {
			var pcs=cs.split("%");
			var s_charge=(current*parseFloat(pcs[0]))/100;
		}else{
			var s_charge=parseFloat(cs).toFixed(2);
		}
				
		var g_total	= current-discount+tax+s_charge;
		
		//bootbox.alert("total :"+current+" Tax : "+tax+" s_charge : "+s_charge);		
		grand_total=parseFloat(g_total).toFixed(2);
		
		//bootbox.alert("grand total : "+grand_total);
		
/* 		$("#total-payable").text(grand_total);
		$("#total").text(current);
		$("#count").text(count); */
		
		$('#cs_con').text(s_charge.toFixed(2));
		$("#ds_con").text(discount.toFixed(2));
		$('#ts_con').text(tax.toFixed(2));
		$("#total-payable").text(grand_total);
		$("#total").text(current);
		$("#count").text(count-1);
		an--;
		row_id=$("#row_"+rw_no);
		row_id.remove()
	});
		
	$("#update-row").click(function(){
		var rw=$('#rwNo').val();
		var op=parseFloat($('#price-'+rw).val());
		var oq=parseInt($('#quantity-'+rw).val());
		var np=parseFloat($('#nPrice').val());
		var nq=parseInt($('#nQuantity').val());
		var row_price=op;
		var row_quantity=oq;
		total=total-(op*oq);
		total=total+(np*nq);
		current=parseFloat(total).toFixed(2);
		count=count-oq;
		count=count+nq;
		
		var ds=$('#discount_val').val();
				
		//handling with or without % for Discount.
		if(ds.indexOf("%")!==-1) {
			var pds=ds.split("%");
			var discount=(current*parseFloat(pds[0]))/100;
		}else{
			var discount=parseFloat(ds).toFixed(2);
		}
		
		//handling with or without % for Tax.
		var ts=$('#tax_val').val();
		if(ts.indexOf("%")!==-1) {
			var pts=ts.split("%");
			var tax=(current*parseFloat(pts[0]))/100;
		}else{
			var tax=parseFloat(ts).toFixed(2);
		}
		
		//handling with or without % for s_charge.
		var cs=$('#scharge_val').val();
		if(cs.indexOf("%")!==-1) {
			var pcs=cs.split("%");
			var s_charge=(current*parseFloat(pcs[0]))/100;
		}else{
			var s_charge=parseFloat(cs).toFixed(2);
		}
		
		var g_total	= current-discount+tax+s_charge;

		
		grand_total=parseFloat(g_total).toFixed(2);
		
		$('#price-'+rw).val(np);
		$('#quantity-'+rw).val(nq);
		if($('#proModalLabel').text().length>13){
			pName=$('#proModalLabel').text().substring(0,13)+'..'
		}else{
			pName=$('#proModalLabel').text()
		}
		$("#total-payable").text(grand_total);
		$("#total").text(current);
		$("#count").text(count-1);
		$('#price_'+rw).text((np*nq).toFixed(2));
		$('#'+rw).text(pName+' @ '+np.toFixed(2));
		
		return false
	});
		
	if(KB==1){
		$("#saletbl").on("focus",".keyboard",function(){key_pad()});
		
		$('.kbp-input').keyboard({
			restrictInput:true,
			preventPaste:true,
			autoAccept:true,
			alwaysOpen:false,
			openOn:'click',
			layout:'costom',
			display:{'a':'\u2714:Accept (Shift-Enter)','accept':'Accept:Accept (Shift-Enter)','b':'\u2190:Backspace','bksp':'Bksp:Backspace','c':'\u2716:Cancel (Esc)','cancel':'Cancel:Cancel (Esc)','clear':'C:Clear'},
			position:{of:$('.ui-kbnum'),my:'center top',at:'center top',at2:'center bottom'},
			usePreview:false,
			customLayout:{'default':['1 2 3 {clear}','4 5 6 .','7 8 9 0','{accept} {cancel}']}
		});
		
		$('.kbq-input').keyboard({
			restrictInput:true,
			preventPaste:true,
			autoAccept:true,
			alwaysOpen:false,
			openOn:'click',
			layout:'costom',
			display:{'a':'\u2714:Accept (Shift-Enter)','accept':'Accept:Accept (Shift-Enter)','b':'\u2190:Backspace','bksp':'Bksp:Backspace','c':'\u2716:Cancel (Esc)','cancel':'Cancel:Cancel (Esc)','clear':'C:Clear'},
			position:{of:null,my:'center top',at:'center top',at2:'center bottom'},
			usePreview:false,
			customLayout:{'default':['1 2 3 {b}','4 5 6 {clear}','7 8 9 0','{accept} {cancel}']}
		});
			
		function key_pad(){
			$('.keyboard').keyboard({
				restrictInput:true,
				preventPaste:true,
				autoAccept:true,
				alwaysOpen:false,
				openOn:'click',
				layout:'costom',
				display:{'a':'\u2714:Accept (Shift-Enter)','accept':'Accept:Accept (Shift-Enter)','b':'\u2190:Backspace','bksp':'Bksp:Backspace','c':'\u2716:Cancel (Esc)','cancel':'Cancel:Cancel (Esc)','clear':'C:Clear'},
				position:{of:null,my:'center top',at:'center top',at2:'center bottom'},
				usePreview:false,
				customLayout:{'default':['1 2 3 {b}','4 5 6 {clear}','7 8 9 0','{accept} {cancel}']},
				beforeClose:function(e,keyboard,el,accepted){
					var before_qty=parseInt(keyboard.originalContent);
					var after_qty=parseInt(el.value);
					var row_id=$(this).attr('id');
					var sp_id=row_id.split("-");
					var id_no=sp_id[1];
					var p='#price-'+id_no;
					var p1='#price_'+id_no;
					var product_price=parseFloat($.trim($(p).val()));
					var row_price=parseFloat($.trim($(p1).text()));
					var gross_total=after_qty*product_price;
					gross_total=parseFloat(gross_total).toFixed(2);
					var b_count=(count-before_qty);
					var a_count=(b_count+after_qty);
					count=a_count;
					var b_total=(total-row_price);
					var a_total=(parseFloat(b_total)+parseFloat(gross_total));
					total=a_total;$(p1).empty();
					$(p1).append(gross_total);
					current=parseFloat(total).toFixed(2);
					var ds=$('#discount_val').val();
					if(ds.indexOf("%")!==-1){
						var pds=ds.split("%");
						var discount=(total*parseFloat(pds[0]))/100;
						var g_total=(total+parseFloat($('#ts_con').text()))-discount;
						$("#ds_con").text(discount.toFixed(2))
					}else{
						var g_total=(total+parseFloat($('#ts_con').text()))-parseFloat(ds);
						$("#ds_con").text(parseFloat(ds).toFixed(2))
					}
					var ts=$('#tax_val').val();
					if(ts.indexOf("%")!==-1){
						var pts=ts.split("%");
						var tax=(total*parseFloat(pts[0]))/100;
						var g_total=(total+tax)-parseFloat($('#ds_con').text());
						$("#ts_con").text(tax.toFixed(2))
					}else{
						var g_total=(total+parseFloat(ts))-parseFloat($('#ds_con').text());
						$("#ts_con").text(parseFloat(ts).toFixed(2))
					}
					grand_total=parseFloat(g_total).toFixed(2);
					$("#total-payable").text(grand_total);
					$("#total").text(current);$("#count").text(count-1)
				}
			})
		}
	}else{    //else of KB=1
		function key_pad(){}
		var before_qty,after_qty;
		$(".nkb-input").live("focus",function(){before_qty=parseInt($(this).val())});
		$(".nkb-input").live("change",function(e){
	
		after_qty=parseInt($(this).val());
		var row_id=$(this).attr('id');
		var sp_id=row_id.split("-");
		var id_no=sp_id[1];
		var p='#price-'+id_no;
		var p1='#price_'+id_no;
		var product_price=parseFloat($.trim($(p).val()));
		var row_price=parseFloat($.trim($(p1).text()));
		var gross_total=after_qty*product_price;
		gross_total=parseFloat(gross_total).toFixed(2);
		var b_count=(count-before_qty);
		var a_count=(b_count+after_qty);
		count=a_count;
		var b_total=(total-row_price);
		var a_total=(parseFloat(b_total)+parseFloat(gross_total));
		total=a_total;
		$(p1).empty();
		$(p1).append(gross_total);
		current=parseFloat(total).toFixed(2);
		
		var ds=$('#discount_val').val();
				
		//handling with or without % for Discount.
		if(ds.indexOf("%")!==-1) {
			var pds=ds.split("%");
			var discount=(current*parseFloat(pds[0]))/100;
		}else{
			var discount=parseFloat(ds).toFixed(2);
		}
		
		//handling with or without % for Tax.
		var ts=$('#tax_val').val();
		if(ts.indexOf("%")!==-1) {
			var pts=ts.split("%");
			var tax=(current*parseFloat(pts[0]))/100;
		}else{
			var tax=parseFloat(ts).toFixed(2);
		}
		
		//handling with or without % for s_charge.
		var cs=$('#scharge_val').val();
		if(cs.indexOf("%")!==-1) {
			var pcs=cs.split("%");
			var s_charge=(current*parseFloat(pcs[0]))/100;
		}else{
			var s_charge=parseFloat(cs).toFixed(2);
		}
				
		var g_total	= current-discount+tax+s_charge;
		
		grand_total=parseFloat(g_total).toFixed(2);
		
		
/* 		$("#total-payable").text(grand_total);
		$("#total").text(current);
		$("#count").text(count-1); */
	
		$('#cs_con').text(s_charge.toFixed(2));
		$("#ds_con").text(discount.toFixed(2));
		$('#ts_con').text(tax.toFixed(2));
		
		$("#total-payable").text(grand_total);
		$("#total").text(current);
		
		$("#count").text(count-1);
	
	
	}) // end of change even
	
	
	}  //end of IF KB==1
		
		
	$(document).bind('keypress',function(e){
		if(e.keyCode==13){
			e.preventDefault();
			return false
		}
	});
	
	function add_row(){
		$('button[id^="product-"]').click(function(){
			if(count>=1000){
				bootbox.alert("Anda mencapai limit 999.");
				return false
			}
			if(an>=51){
				bootbox.alert("Anda sampai limit items! Silahkan lakukan payment dan buat bill baru untuk items berikutnya. Thank you!");
				$('#loading').hide();var divElement=document.getElementById('protbldiv');
				divElement.scrollTop=divElement.scrollHeight;
				return false
			}
			$('#loading').show();

			//append items on table 
			var v=$(this).val();
			item_price = parseFloat(v).toFixed(2);
			var leng=$(this).attr('id').length;
			var last=$(this).attr('id').substr(leng-4);
			var pric='price'+last;
			var quan='quantity'+last;
			var code='code'+last;
			var pr_name=$(this).attr('data-name');
			var prod_name=$.trim(pr_name);
			
			if(prod_name.length>16){
				pName=prod_name.substring(0,16)+'..'
			}else{
				pName=prod_name
			}
			var rcount=count;
			count=rt;
			var newTr=$('<tr id="row_'+count+last+'"></tr>');
			qty_c = count;
			newTr.html('<td class="satu" style="width: 9%;"><button class="del_row" id="del-'+count+last+'" value="'+item_price+'"><i class="glyphicon glyphicon-remove-circle"></i></button></td><td style="width: 53%;"><input type="hidden" class="code" name="product'+count+'" value="'+prod_name+'" id="product-'+count+last+'"><button type="button" class="btn btn-warning btn-block btn-xs prod_name tip text-left" data-name="'+prod_name+'" id="'+count+last+'">&nbsp;&nbsp;'+pName+'-@'+item_price+'</button><span class="printspan">'+prod_name+'</span></td><td style="width: 12%; text-align:left;"><input class="keyboard nkb-input" name="quantity'+count+'" type="text" value="1" id="quantity-'+count+last+'" onclick="this.select();" autocomplete="off"></td><td style="width: 26%;" class="text-right"><input type="hidden" class="price" name="price'+count+'" value="'+item_price+'" id="price-'+count+last+'"><span id="price_'+count+last+'">'+item_price+'</span></td>');
			newTr.appendTo("#saletbl");
			//end of append items on table'
			
			//Total,Tax,Items#,Discount,S-Charge Calculation 
			total+=parseFloat(item_price);
			current=parseFloat(total).toFixed(2);
			
			
			/* var ds=$('#discount_val').val();
			if(ds.indexOf("%")!==-1){
				var pds=ds.split("%");
				var discount=(total*parseFloat(pds[0]))/100;
				var g_total=(total+parseFloat($('#ts_con').text()))-discount;
				$("#ds_con").text(discount.toFixed(2))
			}else{
				var g_total=(total+parseFloat($('#ts_con').text()))-parseFloat(ds);
				$("#ds_con").text(parseFloat(ds).toFixed(2))
			}
			
			var ts=$('#tax_val').val();
			if(ts.indexOf("%")!==-1){
				var pts=ts.split("%");
				var tax=(total*parseFloat(pts[0]))/100;
				var g_total=(total+tax)-parseFloat($('#ds_con').text());
				$("#ts_con").text(tax.toFixed(2))
			}else{
				var g_total=(total+parseFloat(ts))-parseFloat($('#ds_con').text());
				$("#ts_con").text(parseFloat(ts).toFixed(2))
			} */
			
		var ds=$('#discount_val').val();
				
		//handling with or without % for Discount.
		if(ds.indexOf("%")!==-1) {
			var pds=ds.split("%");
			var discount=(current*parseFloat(pds[0]))/100;
		}else{
			var discount=parseFloat(ds).toFixed(2);
		}
		
		//handling with or without % for Tax.
		var ts=$('#tax_val').val();
		if(ts.indexOf("%")!==-1) {
			var pts=ts.split("%");
			var tax=(current*parseFloat(pts[0]))/100;
		}else{
			var tax=parseFloat(ts).toFixed(2);
		}
		
		//handling with or without % for s_charge.
		var cs=$('#scharge_val').val();
		if(cs.indexOf("%")!==-1) {
			var pcs=cs.split("%");
			var s_charge=(current*parseFloat(pcs[0]))/100;
		}else{
			var s_charge=parseFloat(cs).toFixed(2);
		}
				
		var g_total	= current-discount+tax+s_charge;
		
		//bootbox.alert("total :"+current+" Tax : "+tax+" s_charge : "+s_charge);		
		grand_total=parseFloat(g_total).toFixed(2);
		count=rcount;
		//bootbox.alert("grand total : "+grand_total);
		
/* 		$("#total-payable").text(grand_total);
		$("#total").text(current);
		$("#count").text(count); */
		
		$('#cs_con').text(s_charge.toFixed(2));
		$("#ds_con").text(discount.toFixed(2));
		$('#ts_con').text(tax.toFixed(2));
		$("#total-payable").text(grand_total);
		$("#total").text(current);
		
		$("#count").text(count);
		
		count++;rt++;
		an++;
		
		
		
		var divElement=document.getElementById('protbldiv');
		divElement.scrollTop=divElement.scrollHeight;
		$('#loading').hide()
		$('input[name^="quantity'+qty_c+'"]').focus();
			
		})
	} //end of function add_row()
			
			
	$('#scancode').keydown(function(e){
		
		if(e.keyCode==13){if(count>=1000){
			bootbox.alert("Anda mencapai Quantity Limit : 999.");
			return false
		}
		
		if(an>=51){
			bootbox.alert("Maximum Item! Silahkan lakukan payment dan buat payment untuk items selanjutnya. Terima Kasih!");
			$('#loading').hide();
			var divElement=document.getElementById('protbldiv');
			divElement.scrollTop=divElement.scrollHeight;
			return false
		}
		
		$('#loading').show();
			var v=$(this).val();
			$.ajax({
				type:"get",
				async:false,
				url:"process.php?module=pos&view=scan_product",
				data:{code:v},
				dataType:"json",
				success:function(data){
					if(data==null){
						bootbox.alert('Request Failed, Pastikan ID Product Benar dan Coba Lagi!');
						item_price=false
					}else{
						item_price=parseFloat(data.item_price).toFixed(2);
						sproduct_name=data.product_name;
						slast=data.last
					}
				},
				error:function(){
					bootbox.alert('Request Failed, Pastikan ID Product Benar dan Coba Lagi!');
					item_price=false
				}
			});
			
			if(item_price==false){
				$(this).val('');$('#loading').hide();
				return false
			}
			
			if(sproduct_name.length>13){
				pName=sproduct_name.substring(0,13)+'..'
			}else{
				pName=sproduct_name
			}
			
			var rcount=count;count=rt;
			var newTr=$('<tr id="row_'+count+slast+'"></tr>');
			newTr.html('<td class="satu" style="width: 9%;"><button class="del_row" id="del-'+count+slast+'" value="'+item_price+'"><i class="glyphicon glyphicon-remove-circle"></i></button></td><td style="width: 53%;"><input type="hidden" class="code" name="product'+count+'" value="'+sproduct_name+'" id="product-'+count+slast+'"><button type="button" class="btn btn-warning btn-block btn-xs prod_name tip text-left" data-name="'+sproduct_name+'" id="'+count+slast+'">'+pName+' @ '+item_price+'</button><span class="printspan">'+sproduct_name+'</span></td><td style="width: 12%; text-align:center;"><input class="keyboard nkb-input" name="quantity'+count+'" type="text" value="1" id="quantity-'+count+slast+'" onclick="this.select();" autocomplete="off"></td><td style="width: 26%;" class="text-right"><input type="hidden" class="price" name="price'+count+'" value="'+item_price+'" id="price-'+count+slast+'"><span id="price_'+count+slast+'">'+item_price+'</span></td>');
			newTr.appendTo("#saletbl");
			total+=parseFloat(item_price);
			current=parseFloat(total).toFixed(2);
			var ds=$('#discount_val').val();
			
			if(ds.indexOf("%")!==-1){
				var pds=ds.split("%");
				var discount=(total*parseFloat(pds[0]))/100;
				var g_total=(total+parseFloat($('#ts_con').text()))-discount;
				$("#ds_con").text(discount.toFixed(2))
			}else{
				var g_total=(total+parseFloat($('#ts_con').text()))-parseFloat(ds);
				$("#ds_con").text(parseFloat(ds).toFixed(2))
			}
			
			var ts=$('#tax_val').val();
			if(ts.indexOf("%")!==-1){
				var pts=ts.split("%");
				var tax=(total*parseFloat(pts[0]))/100;
				var g_total=(total+tax)-parseFloat($('#ds_con').text());
				$("#ts_con").text(tax.toFixed(2))
			}else{
				var g_total=(total+parseFloat(ts))-parseFloat($('#ds_con').text());
				$("#ts_con").text(parseFloat(ts).toFixed(2))
			}
			
			grand_total=parseFloat(g_total).toFixed(2);
			count=rcount;$("#total-payable").text(grand_total);
			$("#total").text(current);
			$("#count").text(count);
			count++;
			rt++;
			an++;
			var divElement=document.getElementById('protbldiv');
			divElement.scrollTop=divElement.scrollHeight;
			$(this).val('');
			$('#loading').hide();
			e.preventDefault();
			return false}
});
			
			
			
	$("#cancel").click(function(){
		bootbox.confirm("Anda yakin membatalkan transaksi (jika ada) ?",
		function(result){
			if(result==true){
				$("#saletbl").empty();
				count=1,total=0,tax_value=0,an=1;
				$("#ds_con").text('0.00');
				$('#ts_con').text('0.00');
				$("#total-payable").text('0.00');
				$("#total").text('0.00');
				$("#count").text(count-1)
			}
		})
	}); // end of cancel sale
	
	
	$("#payment").click(function(){
		$("#pay").empty();
		var g_total=(total+parseFloat($('#ts_con').text()))-parseFloat($('#ds_con').text());
		twt=parseFloat(g_total).toFixed(2);
		count=count-1;
		if(isNaN(twt)||twt=='0.00'){
			bootbox.alert('Tidak ada item yang dapat dibayar. Pilih Items !.');
			count=count+1;
			return false
		}
		twt=parseFloat(twt).toFixed(2);
		$('#twt').text(twt);
		$('#fcount').text(count);
		$('#is_delete').val('91');
		$('#payModal').modal();
		count=count+1;
		$('#total_item').val(count);
		$('.pcustomer').change(function(){
			$('#customer').val($(this).val())
		});
		$('#paid-amount').change(function(){
		$('#paid_val').val($(this).val())
		});
			
		$('#pcc').change(function(){$('#cc_no_val').val($(this).val())});
		$('#pcc_holder').change(function(){$('#cc_holder_val').val($(this).val())});
		$("#paid_by").change(function(){
			var p_val=$(this).val();
			$('#rpaidby').val(p_val);
			if(p_val=='CASH'){
				$('.pcc').hide();
				$('.pcash').show();
				$('input[id^="paid-amount"]').keydown(function(e){
					paid=$(this).val();
					if(e.keyCode==13){
						if(paid<total){
							bootbox.alert('Pembayaran kurang dari nilai bill');
							return false
						}
						$("#balance").empty();
						var balance=paid-twt;balance=parseFloat(balance).toFixed(2);$("#balance").append(balance);e.preventDefault();return false
					}
				})
			}else{
				$('.pcash').hide();
				$('.pcc').show();
				$('#pcc').focus();	
			}
			
		}); //enf of paid by
			
		if(KB==1){
			$('#paid-amount, kb-input').keyboard({
			restrictInput:true,
			preventPaste:true,
			autoAccept:true,
			alwaysOpen:false,
			openOn:'click',
			layout:'costom',
			display:{'a':'\u2714:Accept (Shift-Enter)','accept':'Accept:Accept (Shift-Enter)','b':'\u2190:Backspace','bksp':'Bksp:Backspace','c':'\u2716:Cancel (Esc)','cancel':'Cancel:Cancel (Esc)','clear':'C:Clear'},
			position:{of:null,my:'center top',at:'center top',at2:'center bottom'},
			usePreview:false,
			customLayout:{'default':['1 2 3 {clear}','4 5 6 .','7 8 9 0','{accept} {cancel}']},
			beforeClose:function(e,keyboard,el,accepted){
				var paid=parseFloat(el.value);
				if(paid<twt){
					bootbox.alert('Pembayaran lebih kecil dari Nilai BILL');$(this).val('');return false
				}
				$("#balance").empty();
				var balance=paid-twt;
				balance=parseFloat(balance).toFixed(2);
				$("#balance").append(balance)
			}
			})
		}else{
			$("#payModal").on("change",'#paid-amount',function(){
				var paid=parseFloat($(this).val());
				if(paid<twt){
					bootbox.alert('Pembayaran lebih kecil dari Nilai BILL');
					$(this).val('');
					return false
				}
				$("#balance").empty();
					var balance=paid-twt;
					balance=parseFloat(balance).toFixed(2);
					$("#balance").append(balance)
			})
		} //end of KB==1
		
		$('#submit-sale').click(function(){$('#submit').trigger('click')})
	});//end of payment
			
		
	//save as order
/*	$('#hold').click(function(){
		
		if(count<=1){
			bootbox.alert('Tidak ada items yang bisa di-save sebagai orders. Pilih Items !');
			return false
		}
		
		suspend=$('<span></span>');$('#is_delete').val('91');
		suspend.html('<input type="hidden" name="suspend" value="yes" />');
		suspend.appendTo("#hidesuspend");
		$('#total_item').val(count);
		$('#susModal').modal();
		$('.pcustomer').change(function(){
			$('#customer').val($(this).val())
		});
					
		$('#hold_ref_v').change(function(){
			$('#hold_ref').val($(this).val())
		});
				
		$('#submit-hold').click(function(){
			if($('#hold_ref_v').val()!=''){
				$('#submit').trigger('click')
			}else{
				bootbox.alert('Ketik Reference ORder');
				return false
			}
		})
	});  */	
	//end of hold

	//load suspended bill
	/* $.ajax({
		type:"post",async:false,dataType:"json",url:"process.php?module=pos&view=getparams",
		data:{id:'1'},
		success:function(data){
			if(data!=null){
				
				if(data.sale_data!="undefined"){
					sale_data=data.sale_data
				}else{
					sale_data="<tbody></tbody>"
				}
				
				if(data.count!=null){
					count=parseInt(data.count)
				}else{
					count=1
				}
				
				if(data.customer_id!=null){
					customer_id=data.customer_id
				}else{
					customer_id=''
				}
				
				if(data.hold_ref!=null){
					hold_ref=data.hold_ref
				}else{
					hold_ref=''
				}
				
				if(data.tax!=null){
					tax=data.tax
				}else{
					tax=0
				}
				
				if(data.total_tax!=null){
					total_tax=parseFloat(data.total_tax)
				}else{
					total_tax=0
				}
				
				if(data.discount!=null){
					discount=data.discount
				}else{
					discount=0
				}
				
				if(data.total_discount!=null){
					total_discount=parseFloat(data.total_discount)
				}else{
					total_discount=0
				}
				
				if(data.inv_total!=null){
					total=parseFloat(data.inv_total)
				}else{
					total=0
				}
				
				if(data.g_total!=null){
					g_total=parseFloat(data.g_total)
				}else{
					g_total=0
				}
			}else{
				sale_data="<tbody></tbody>";
				count=1;
				customer_id='';
				hold_ref='';
				tax=0;
				total_tax=0;
				discount=0;
				total_discount=0;
				total=0;
				g_total=0;0
			}
		},
		
		error:function(){
			sale_data="<tbody></tbody>";
			count=1;
			customer_id='';
			hold_ref='';
			tax=0;total_tax=0;discount=0;total_discount=0;total=0;g_total=0
		}
	});  */
	//end of load suspended bill
	/* 
		
	var sr=1;
	if (sale_data!="<tbody></tbody>"){
	$.each(sale_data,function(index,k){
		if(k.product_name.length>13){
			pName=k.product_name.substring(0,13)+'..'
		}else{
			pName=k.product_name
		}
		var item_price=k.gross_total/k.quantity;
		var newTr=$('<tr id="row_'+sr+k.id+'"></tr>');
		newTr.html('<td class="satu" style="width: 9%;"><button class="del_row" id="del-'+sr+k.id+'" value="'+item_price+'"><i class="glyphicon glyphicon-remove-circle"></i></button></td><td style="width: 53%;"><input type="hidden" class="code" name="product'+sr+'" value="'+k.product_name+'" id="product-'+sr+k.id+'"><button type="button" class="btn btn-warning btn-block btn-xs prod_name tip text-left" data-name="'+k.product_name+'" id="'+sr+k.id+'">'+pName+' @ '+item_price+'</button><span class="printspan">'+k.product_name+'</span></td><td style="width: 12%; text-align:center;"><input class="keyboard nkb-input" name="quantity'+sr+'" type="text" value="'+k.quantity+'" id="quantity-'+sr+k.id+'" onclick="this.select();" autocomplete="off"></td><td style="width: 26%;" class="text-right"><input type="hidden" class="price" name="price'+sr+'" value="'+item_price+'" id="price-'+sr+k.id+'"><span id="price_'+sr+k.id+'">'+k.gross_total+'</span></td>');
		newTr.appendTo("#saletbl");
		sr++
	});
	}
		
	$('#discount_val').val(discount);
	$('.pcustomer').val(customer_id);
	$('#hold_ref_v').val(hold_ref);
	$('#hold_ref').val(hold_ref);
	$('#customer').val(customer_id);
	$('#tax_val').val(tax);
	
	 
	count=sr;
	rt=sr;
	$("#count").text(count-1);
	$("#ts_con").text(parseFloat(total_tax).toFixed(2));
	$("#ds_con").text(parseFloat(total_discount).toFixed(2));
	$("#total").text(parseFloat(total).toFixed(2));
	$("#total-payable").text(parseFloat(g_total).toFixed(2)); */
});


if(DTIME){
		function sivamtime(){
			now=new Date();
			var month_names=new Array();
			month_names[month_names.length]="January";
			month_names[month_names.length]="February";
			month_names[month_names.length]="March";
			month_names[month_names.length]="April";
			month_names[month_names.length]="May";
			month_names[month_names.length]="June";
			month_names[month_names.length]="July";
			month_names[month_names.length]="August";
			month_names[month_names.length]="September";
			month_names[month_names.length]="October";
			month_names[month_names.length]="November";
			month_names[month_names.length]="December";
			
			var day_names=new Array();
			day_names[day_names.length]="Sunday";
			day_names[day_names.length]="Monday";
			day_names[day_names.length]="Tuesday";
			day_names[day_names.length]="Wednesday";
			day_names[day_names.length]="Thursday";
			day_names[day_names.length]="Friday";
			day_names[day_names.length]="Saturday";
			hour=now.getHours();
			min=now.getMinutes();
			sec=now.getSeconds();
			if(min<=9){min="0"+min}
			if(sec<=9){sec="0"+sec}
			if(hour>12){
				hour=hour-12;
				add="PM"
			}else{
				hour=hour;add="AM"
			}
			if(hour==12){
				add="PM"
			}
			time=day_names[now.getDay()]+", "+now.getDate()+" "+month_names[now.getMonth()]+" "+now.getFullYear()+", "+((hour<=9)?"0"+hour:hour)+":"+min+":"+sec+" "+add;
			
			if(document.getElementById){
				document.getElementById('cur-time').innerHTML=time
			}else if(document.layers){
				document.layers.theTime.document.write(time);
				document.layers.theTime.document.close()
			}
			setTimeout("sivamtime()",1000)
		}
		window.onload=sivamtime
}				


function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
    chars = chars || "\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
    chars = chars || "\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
//end of javascript

</script>
</body>
</html>


<?php 

mysql_close($link);

} ?>